package udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPClient {
    private DatagramSocket datagramSocket;
    private String address;
    private int port;
    public UDPClient(String address, int port) throws SocketException {
        this.address = address;
        this.port = port;
        datagramSocket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动：");
        Scanner in = new Scanner(System.in);
        while(true) {
            System.out.print("请输入：");
            String result = in.nextLine();
            //构造请求数据报
            DatagramPacket resultPacket = new DatagramPacket(result.getBytes(), result.getBytes().length, InetAddress.getByName(address), port);
            //发送请求
            datagramSocket.send(resultPacket);
            //创建响应数据报接收响应
            DatagramPacket respondPacket = new DatagramPacket(new byte[65536], 65536);
            datagramSocket.receive(respondPacket);
            String response = new String(respondPacket.getData(), 0, respondPacket.getLength());
            System.out.println("服务器返回：" + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPClient client = new UDPClient("127.0.0.1", 8090);
        client.start();
    }
}
